package cfi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.arnx.jsonic.JSON;
import cfi.jdo.CoffeeCustomer;
import cfi.jdo.PMF;
import cfi.jdo.Purchase;
import cfi.jdo.Ticket;
import cfi.util.CfUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class CfiTicketServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String errorMessage = null;
		String joson = null;
		String num = req.getParameter("num");
		String cost = req.getParameter("cost");
		String idm = req.getParameter("idm");
		if (idm == null || idm == "" || num == null || num == ""
				|| cost == null || cost == "") {
			errorMessage = "チケット情報取得失敗。";
		} else {
			// ユーザ取得
			PersistenceManager pm = PMF.get().getPersistenceManager();
			// デタッチ宣言すると。、クローズしてもＯＫらしい。
			pm.setDetachAllOnCommit(true);
			CoffeeCustomer c = null;
			Ticket t = null;
			List<Ticket> tList = null;
			Transaction tx = null;
			try {
				tx = pm.currentTransaction();
				tx.begin();
				// 顧客ＧＥＴ
				c = pm.getObjectById(CoffeeCustomer.class, idm);
				tList = c.getTicketList();
				// チケットＪＤＯ作成
				t = new Ticket(CfUtil.getJPDate(), Integer.parseInt(num),
						Integer.parseInt(num), c);
				// ユーザのチケットの更新
				if (tList == null || tList.size() == 0) {
					tList = new ArrayList<Ticket>();
				}
				tList.add(t);
				c.setTicketList(tList);
				pm.makePersistent(c);
				//TODO 親子だからいいのか？
				//pm.makePersistent(t);
				tx.commit();
				joson = JSON.encode(t);
			} catch (Exception e) {
				e.printStackTrace();
				errorMessage = "登録に失敗。";
			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		}
		if (joson != null) {
			resp.setContentType("application/json; charset=UTF-8");
			resp.getWriter().println(joson);
		} else {
			resp.setContentType("text/plain");
			resp.setContentType("text/html;charset=UTF-8");
			resp.getWriter().println(errorMessage);
		}
	}
}
